package cl.tinet.finalexam.ejb.reserves;

import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import cl.tinet.finalexam.dao.SystemBDDAO;
import cl.tinet.finalexam.exceptions.ReserveCollitionException;
import cl.tinet.finalexam.exceptions.ReserveNotFoundException;
import cl.tinet.finalexam.exceptions.RoomNotFoundException;
import cl.tinet.finalexam.exceptions.UserNotFoundException;
import cl.tinet.finalexam.model.ClassroomModel;
import cl.tinet.finalexam.model.ReserveModel;
import cl.tinet.finalexam.model.UserModel;

/**
 * 
 * Bean de Reservas.
 *
 * @author tinet
 */
@Stateless(mappedName = "reservebeanImpl", name = "reservebeanImpl")
public class ReservesBeanImpl implements ReservesBeanInterface {

    /**
     * Persisetncia Base de datos.
     */
    @PersistenceContext(unitName = "MysqlDS")
    private EntityManager em;

    /**
     * DAO
     */
    SystemBDDAO dataDAO;

    @PostConstruct
    public void init() {
        dataDAO = new SystemBDDAO(em);
    }

    /**
     * {@inheritDoc}
     */
    public void addReserve(int usernameOfReserve, ReserveModel reserveToAdd)
            throws ReserveCollitionException, RoomNotFoundException,
            UserNotFoundException {

        UserModel userTemp = null;
        ClassroomModel roomTemp = null;

        roomTemp = dataDAO.searchByRoomID(reserveToAdd.getRoomCode());
        userTemp = dataDAO.searchByUserID(usernameOfReserve);

        if (userTemp != null) {
            if (roomTemp != null) {
                if (!userTemp.getReservesCollections().contains(reserveToAdd)) {
                    reserveToAdd.setClassroomEntity(roomTemp);
                    reserveToAdd.setUserEntity(userTemp);
                    userTemp.getReservesCollections().add(reserveToAdd);
                    dataDAO.addUser(userTemp);
                } else {
                    throw new ReserveCollitionException(
                            String.valueOf(reserveToAdd.getIdReserve()));
                }
            } else {
                throw new RoomNotFoundException(String.valueOf(reserveToAdd
                        .getIdReserve()));
            }
        } else {
            throw new UserNotFoundException(String.valueOf(usernameOfReserve));
        }

    }

    /**
     * {@inheritDoc}
     */
    public void removeReserve(int reserveToRemove) throws ReserveNotFoundException {

        ReserveModel reserveTempDB = dataDAO.searchByReserveID(reserveToRemove);

        if (!(reserveTempDB == null)) {
            dataDAO.removeReserve(reserveTempDB);
        }else{
            throw new ReserveNotFoundException(String.valueOf(reserveToRemove));
        }
    }

}
